#!/usr/bin/env python
# encoding: utf-8
# Date: 2017-06-18 17:09:08
# file:views.py
# Email: wang521kang@outlook.com
# Author: 王康


from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User

from utils.views import request_parms_check, get_json


@request_parms_check(username=('用户名', 'r'), password=('密码', 'r'))
def create_user(request, username, password):
    """
    创建普通用户
    :param request: 
    :param username: 
    :param password: 
    :return: 
    """
    query = User.objects.filter(username=username).count()
    if query == 0:
        user = User.objects.create_user(username, '', password)
        user.is_superuser = False
        user.is_staff = False
        user.save()
        return get_json(True, '创建成功')
    else:
        return get_json(True, '用户名已存在')


@request_parms_check(username=('用户名', 'r'), password=('密码', 'r'))
def create_admin(request, username, password):
    query = User.objects.filter(username=username).count()
    if query == 0:
        user = User()
        user.username = username
        user.set_password(password)
        user.is_staff = True
        user.is_superuser = False
        user.save()
        return get_json(True, '创建成功')
    else:
        return get_json(True, '用户名已存在')


@request_parms_check(username=('用户名', 'r'), password=('密码', 'r'))
def user_login(request, username, password):
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            return get_json(True, '')
        else:
            return get_json(False, '用户名或密码不存在')
    else:
        return get_json(False, '用户名或密码不存在')


def user_logout(request):
    logout(request)
    return get_json(True, '')
